<template>
  <div>
    <el-form ref="printerRef" :model="form" label-width="60px">
      <el-space wrap>
        <span> 模板配置项:</span>
        <el-button type="primary" icon="Plus" @click="addHandleRow"> + </el-button>
      </el-space>
      <div style="height: 20px"></div>
      <div v-for="(item, index) in form.value" :key="index">
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="item.title"
              :rules="{
                required: true,
                message: 'Name is required',
                trigger: 'blur',
              }"
              :prop="'value.' + index + '.value'"
            >
              <el-select
                v-if="item.id == 4 && Array.isArray(item.value)"
                v-model="imgValue"
                class="m-2"
                placeholder="Select"
              >
                <el-option
                  v-for="ite in item.value"
                  default="111"
                  :key="ite.value"
                  :label="ite.label"
                  :value="ite"
                />
              </el-select>

              <el-image
                v-if="item.id == 4 && Array.isArray(item.value)"
                fit="contain"
                :src="imgValue.img"
              />
              <div class="m-4" v-if="item.id == 5 && Array.isArray(item.value)">
                <p>数据源选择</p>
                <el-select
                  v-model="textValue"
                  class="m-2"
                  placeholder="Select"
                  style="width: 240px"
                  @change="handleChange"
                >
                  <el-option
                    v-for="ite in item.value"
                    :key="ite.value"
                    :label="ite.label"
                    :value="ite"
                  />
                </el-select>
                <br />
                <el-text class="mx-1" size="large">{{ textValue.desc }}</el-text>
              </div>
              <div class="m-4" v-else-if="item.id == 6 && Array.isArray(item.value)">
                <p>数据源选择</p>
                <el-select
                  v-model="selectTableValue"
                  class="m-2"
                  placeholder="Select"
                  style="width: 240px"
                  @change="selectTableChange"
                >
                  <el-option
                    v-for="ite in item.value"
                    :key="ite.value"
                    :label="ite.label"
                    :value="ite"
                  />
                </el-select>
                <br />
                <br />
                <el-table :data="selectTableValue.tableData" style="width: 100%">
                  <el-table-column prop="id" label="ID" width="230" />
                  <el-table-column prop="name" label="名称" width="230" />
                  <el-table-column prop="address" label="数据" />
                </el-table>
              </div>

              <!-- 确保 item.value 是字符串或数字时才绑定到 el-input -->
              <el-input
                v-else-if="typeof item.value === 'string' || typeof item.value === 'number'"
                v-model="item.value"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="padding-left: 30px">
            <el-button icon="Minus" @click="delHandleRow(index)">-</el-button>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-row class="mb-4">
      <el-button type="primary" @click="dialogVisible = true">保存模板</el-button>
      <el-dialog v-model="dialogVisible" title="确定保存模板" width="30%" draggable>
        <br />
        <div class="tempDialog">
          <span>模板名称：</span>
          <el-input class="tempinput" v-model="templatedata" placeholder="请输入模板名称" />
        </div>
        <br />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="ok"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-row>
  </div>
</template>
<style scoped lang="scss">
.tempDialog {
  display: flex;
  justify-content: start;
  width: 100%;
  .tempinput {
    width: calc(100% - 100px);
  }
}
</style>
<script lang="ts" setup>
import { useProfileConfigStore } from '@/store'
import image1 from '@/assets/images/image1.png'
import image2 from '@/assets/images/image2.png'
// 获取 store 实例
const profileConfigStor = useProfileConfigStore()
onMounted(() => {
  console.log(`the component is now mounted.`)
})
const templatedata = ref('模板1')
const dialogVisible = ref(false)

const imgValue = ref({
  value: 'Option1',
  label: '实验类型A回路图',
  img: image1,
})
const tempId = ref(6)

let tempDataArr: { name: string; value: any; }[] = []

const addHandleRow = () => {
  tempId.value += 1
  form.value.value.push({ title: '规则', value: '', id: tempId.value })
}

const delHandleRow = (index: any) => {
  form.value.value.splice(index, 1)
}
const selectTableChange = (value: any) => {
  selectTableValue.value = value
}
const handleChange = (value: any) => {
  textValue.value = value
}
const ok = () => {
  dialogVisible.value = false
  let subData = JSON.parse(JSON.stringify(form.value))
  let tempData = {
    name: templatedata.value,
    value: subData.value,
  }
  subData.value.forEach((item: any) => {
    if (item.id === 4) {
      item.value = imgValue.value // 动态赋值文本源
    }
    if (item.id === 5) {
      item.value = textValue.value // 动态赋值文本源
    }
    if (item.id === 6) {
      item.value = selectTableValue.value // 动态赋值表格源
    }
  })
  // 使用 Map 替代对象，避免索引签名问题
  const tempDataMap = new Map<string, typeof tempData>()
  tempDataArr.forEach((data) => {
    tempDataMap.set(data.name, data) // 如果存在同名模板，则覆盖
  })
  tempDataMap.set(tempData.name, tempData) // 添加当前模板
  // 将 Map 转换回数组
  tempDataArr = Array.from(tempDataMap.values())
  console.log('subData!', tempDataArr)
  profileConfigStor.tempData = tempDataArr
  console.log('subData2', profileConfigStor.tempData)
}

const textValue = ref({
  value: '设备A',
  label: '设备A',
  desc: '电压为：{$source.voltage}，电流为：{$source.current}。',
})
const selectTableValue = ref({
  value: '设备A',
  label: '设备A',
  tableData: [
    {
      id: '1',
      name: '数据A',
      address: '{$source.data}',
    },
    {
      id: '2',
      name: '数据B',
      address: '{$source.data}',
    },
    {
      id: '3',
      name: '数据C',
      address: '{$source.data}',
    },
  ],
})
const form = ref({
  value: [
    { title: '标题', value: 'xx1实验', id: 1 },
    { title: '时间', value: '启动实验的时间', id: 2 },
    { title: '文本', value: '试验回路Test circuit：', id: 3 },
    {
      title: '图像',
      value: [
        {
          value: 'optionA',
          label: '实验类型A回路图',
          img: image1,
        },
        {
          value: 'optionB',
          label: '实验类型B回路图',
          img: image2,
        },
      ],
      id: 4,
    },
    {
      title: '文本',
      value: [
        {
          value: '设备A',
          label: '设备A',
          desc: '电压为：{$source.voltage}，电流为：{$source.current}。',
        },
        {
          value: '设备B',
          label: '设备B',
          desc: '电压为：{$source.voltage}，电流为：{$source.current}。',
        },
        {
          value: '设备C',
          label: '设备C',
          desc: '电压为：{$source.voltage}，电流为：{$source.current}。',
        },
      ],
      id: 5,
    },
    {
      title: '表格',
      value: [
        {
          value: '设备A',
          label: '设备A',
          tableData: [
            {
              id: '1',
              name: '数据A',
              address: '{$source.data}',
            },
            {
              id: '2',
              name: '数据B',
              address: '{$source.data}',
            },
            {
              id: '3',
              name: '数据C',
              address: '{$source.data}',
            },
          ],
        },
        {
          value: '设备B',
          label: '设备B',
          tableData: [
            {
              id: '1',
              name: '数据C',
              address: '{$source.data}',
            },
            {
              id: '2',
              name: '数据D',
              address: '{$source.data}',
            },
            {
              id: '3',
              name: '数据E',
              address: '{$source.data}',
            },
          ],
        },
        {
          value: '设备C',
          label: '设备C',
          tableData: [
            {
              id: '1',
              name: '数据E',
              address: '{$source.data}',
            },
            {
              id: '2',
              name: '数据D',
              address: '{$source.data}',
            },
            {
              id: '3',
              name: '数据C',
              address: '{$source.data}',
            },
          ],
        },
      ],
      id: 6,
    },
  ],
})
</script>
